package com.ruan.config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruan.common.Code;
import com.ruan.common.MessageConstant;
import com.ruan.common.Result;
import com.ruan.exception.BusinessException;
import com.ruan.mapper.AdminMapper;
import com.ruan.mapper.CommonUserMapper;
import com.ruan.pojo.Admin;
import com.ruan.pojo.CommonUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminAuthorizeService implements UserDetailsService {


    //https://blog.csdn.net/qq_56769991/article/details/122881160?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168158149316800226519949%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168158149316800226519949&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-6-122881160-null-null.142^v83^insert_down38,239^v2^insert_chatgpt&utm_term=org.springframework.security.access.AccessDeniedException%3A%20%E4%B8%8D%E5%85%81%E8%AE%B8%E8%AE%BF%E9%97%AE&spm=1018.2226.3001.4187
    @Resource
    private AdminMapper adminMapper;

    @Resource
    private CommonUserMapper commonUserMapper;

    //作用是根据用户名查询数据库中的用户信息，
    // 然后封装成一个User对象返回，用于Spring Security进行身份验证和授权
    // 如果用户存在，则返回一个UserDetails对象，否则抛出异常。
    @Override
    //Spring Security 调用 UserDetailsService 的 loadUserByUsername 方法，根据用户名加载用户
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{//
//        System.out.println("登陆的username是:"+username);
        //如果用户名里有admin字符，则去掉
//        if (username.contains("admin")){
//            //去掉admin字符
//            username = username.replace("admin","");
//        }
//        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Admin::getUsername,username+"admin");//
//        int count = adminMapper.selectCount(queryWrapper);
//        if(count == 1){
//            username = username + "admin";
//        } else if(count > 1){
//            throw new BusinessException(Code.LOGIN_ERR,
//                    "该账号重复，请联系管理员！");
//        }
//        =0就不是管理员登录，后面验证普通用户
//        Admin admin1 = adminMapper.selectOne(queryWrapper);
//        System.out.println("admin1是: "+admin1);
//        if(admin1 != null){
//            username = username + "admin";
//        }

        if (username.contains("adminRole")){
            LambdaQueryWrapper<Admin> adminWrapper = new LambdaQueryWrapper<>();
            adminWrapper.eq(Admin::getUsername,username);
            adminWrapper.ne(Admin::getStatus,Admin.Status.pass);
            int count1 = adminMapper.selectCount(adminWrapper);
            if(count1 > 0){
                throw new BusinessException(Code.LOGIN_ERR,
                        MessageConstant.LOGIN_ERR_AUDIT);
            }
            LambdaQueryWrapper<Admin> adminWrapper1 = new LambdaQueryWrapper<>();
            adminWrapper1.eq(Admin::getUsername,username);
            adminWrapper1.eq(Admin::getStatus,Admin.Status.pass);
            int count2 = adminMapper.selectCount(adminWrapper1);
            if(count2 == 0){
                throw new BusinessException(Code.LOGIN_ERR,
                        "该账号不存在");
            }else if(count2 > 1){
                throw new BusinessException(Code.LOGIN_ERR,
                        "该账号重复，请联系管理员！");
            }
            Admin admin = adminMapper.selectOne(adminWrapper1);

            if (admin!=null) {
                List<GrantedAuthority> authorityList = new ArrayList<>();
                //创建一个包含"ROLE_ANONYMOUS"角色的GrantedAuthority列表。
                authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//ROLE_ANONYMOUS

                //然后在@Controller上添加@PreAuthorize("hasRole('ROLE_ADMIN')")注解，
                //如果用户没有该权限，Spring Security 会阻止请求的访问，通常会返回一个 403 (Forbidden) 错误
                //还要引入。。。 等一些表？？？

                //使用org.springframework.security.core.userdetails.User类创建一个User对象，
                // 包含用户名、密码和权限列表。
                //System.out.println("admin.getPassword()是："+admin.getPassword());
                User user = new org.springframework.security.core.userdetails.User
                        (username,admin.getPassword(),authorityList);
                //System.out.println("user是："+user);
                //返回一个UserDetails对象，包含用户名、密码和权限列表
                //User 对象是用来表示已认证用户的，它在成功登录后会存储在 SecurityContext 中
                return user;//返回这个User对象
//      先进入到AdminAuthorizeService的loadUserByUsername，
//      然后就到SecurityConfig里的onAuthenticationSuccess，
//      那边用了equal("admin")导致停在这里(导致管理员不能注册多个)
//                return User
//                        .withUsername(username)
//                        .password(admin.getPassword())
//                        .roles("ADMIN")
//                        .build();
            }else {//admin=null
                throw new BusinessException(Code.LOGIN_ERR,
                        MessageConstant.LOGIN_ERR_PASS);//
            }
        }//用户名不是"admin"

        LambdaQueryWrapper<CommonUser> commonUserWrapper = new LambdaQueryWrapper<>();
        commonUserWrapper.eq(CommonUser::getUsername,username);//查询CommonUser表中的记录。
        Integer count = commonUserMapper.selectCount(commonUserWrapper);
        if(count == 0){
            throw new BusinessException(Code.LOGIN_ERR,
                    "账号不存在");
        }else if(count > 1){
            throw new BusinessException(Code.LOGIN_ERR,
                    "该账号名重复，请联系管理员！");
        }
        CommonUser commonUser = commonUserMapper.selectOne(commonUserWrapper);
        if (commonUser!=null){
            if (commonUser.getStatus().equals("禁用")){
                throw new BusinessException(Code.LOGIN_ERR,
                        MessageConstant.LOGIN_ERR_STATUS);
            }
            List<GrantedAuthority> authorityList=new ArrayList<>();
            //创建一个包含"ROLE_COMMON_USER"角色的GrantedAuthority列表。
            authorityList.add(new SimpleGrantedAuthority("ROLE_COMMON_USER"));
            //使用org.springframework.security.core.userdetails.User类创建一个User对象，
            // 包含用户名、密码和权限列表
            User user = new org.springframework.security.core.userdetails.User
                    (username,commonUser.getPassword(),authorityList);
            return user;
//            return User
//                    .withUsername(username)
//                    .password(commonUser.getPassword())
//                    .roles("COMMON_USER")
//                    .build();
        }else {//commonUser=null
            throw new BusinessException(Code.LOGIN_ERR,
                    MessageConstant.LOGIN_ERR_PASS);
        }
    }
}
